﻿using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using OpenDeploy.Client.Dialogs;
using OpenDeploy.Client.Helper;
using OpenDeploy.Domain;
using OpenDeploy.Infrastructure;
using OpenDeploy.SQLite;

namespace OpenDeploy.Client.Models;

/// <summary> 主窗体视图模型 </summary>
public partial class MainViewModel(SolutionRepository solutionRepository) : ObservableObject
{
    /// <summary> 解决方案仓储 </summary>
    private readonly SolutionRepository solutionRepository = solutionRepository;

    /// <summary> 解决方案集合 </summary>
    [ObservableProperty]
    private List<SolutionViewModel> solutions = default!;

    /// <summary> 解决方案Git路径 </summary>
    [ObservableProperty]
    private string solutionGitPath = string.Empty;

    /// <summary> 初始化 </summary>
    public async Task InitAsync()
    {
        await Task.Run(async () =>
        {
            await solutionRepository.InitAsync();
            await GetSolutionViewModelAsync();
        });
    }

    /// <summary> 加载解决方案视图模型 </summary>
    private async Task GetSolutionViewModelAsync()
    {
        var solutions = await solutionRepository.GetSolutionsAsync();
        var solutionViewModels = solutions.Select(solution =>
        {
            var solutionVM = new SolutionViewModel
            {
                SolutionId = solution.Id,
                GitRepositoryPath = solution.GitRepositoryPath,
                SolutionName = solution.SolutionFileName,
                SolutionDisplayName = solution.SolutionDisplayName,
            };
            solutionVM.AllProjects = solution.Projects.Select(p => new ProjectViewModel
            {
                SolutionVM = solutionVM,
                ProjectId = p.Id,
                ProjectName = p.ProjectName,
                ProjectDir = p.ProjectDir,
                ReleaseDir = p.ReleaseDir,
                IsWeb = p.IsWeb,
                IsEnabled = p.IsEnabled,
                ServerIp = p.ServerIp,
                ServerPort = p.ServerPort,
            }).ToList();

            //默认只显示Web项目和启用的
            solutionVM.Projects = new System.Collections.ObjectModel.ObservableCollection<ProjectViewModel>
            (
                solutionVM.AllProjects.Where(a => a.IsWeb && a.IsEnabled)
            );

            return solutionVM;
        }).ToList();

        await Application.Current.Dispatcher.InvokeAsync(() =>
        {
            Solutions = solutionViewModels;
        });
    }


    /// <summary> 配置解决方案弹窗 </summary>
    private Dialog? configSolutionDialog;

    /// <summary> 打开配置解决方案弹窗 </summary>
    [RelayCommand]
    public void OpenConfigSolutionDialog()
    {
        SolutionGitPath = string.Empty;
        configSolutionDialog = Dialog.Show(new SolutionConfigDialog(this));
    }

    /// <summary> 确定配置解决方案 </summary>
    [RelayCommand]
    private async Task OkConfigSolution()
    {
        try
        {
            if (!GitHelper.IsValidRepository(SolutionGitPath))
            {
                throw new Exception("非法的Git仓储路径");
            }
        }
        catch (Exception ex)
        {
            Growl.ClearGlobal();
            Growl.WarningGlobal(ex.Message);
            return;
        }

        var loading = Loading.Show();

        try
        {
            await Task.Run(async () =>
            {
                //发现解决方案
                var solutions = SolutionManager.DetectSolutions(SolutionGitPath);

                //持久化到数据库
                await solutionRepository.AddSolutionsAsync(solutions);

                //重新加载解决方案
                await GetSolutionViewModelAsync();
            });

            Growl.SuccessGlobal("操作成功");
        }
        finally
        {
            loading.Close();
            configSolutionDialog?.Close();
        }
    }

}
